<!-- 编辑修改平台账户信息 -->
<script setup lang="ts">
// import { ipcMain } from 'electron'
const { ipcRenderer } = require('electron')

const [visible, toggleVisible] = useToggle(false)

const isEdit = ref(false)

const rowIndex = ref<any>(undefined)

const tableData = ref<any[]>([])

const emit = defineEmits<{
  (e: 'refresh'): void
}>()

const form = ref({
  platformName: '',
  platformUrl: '',
  platformAccount: ''
})

const pureForm = () => {
  return {
    platformName: '',
    platformUrl: '',
    platformAccount: ''
  }
}

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑平台账户' : '新增平台账户'
})

function onCancel() {
  toggleVisible(false)
  form.value = pureForm()
}

function onSubmit() {
  // 通知主进程保存数据
  // const params = JSON.stringify(form.value)
  isEdit.value ? (tableData.value[rowIndex.value] = form.value) : tableData.value.push(form.value)
  const params = JSON.stringify(tableData.value)
  console.log('params', JSON.parse(params))

  ipcRenderer.send('saveTableData', params)
  form.value = pureForm()
  emit('refresh')
  toggleVisible(false)
}

defineExpose({
  async open(data: [], index?: number, item?: any) {
    tableData.value = data || []
    if (item) {
      isEdit.value = true
      rowIndex.value = index
      const data = ipcRenderer.send('getData')
      ipcRenderer.on('responseTableData', (event, data) => {
        console.log('编辑弹窗收到主进程的响应数据:', data)
        tableData.value = data
      })
      form.value = item
    } else {
      form.value = pureForm()
    }
    toggleVisible(true)
  }
})
</script>
<template>
  <t-dialog v-model:visible="visible" :header="dialogTitle" width="400px">
    <!-- <div class="flex justify-center"> -->
    <div>
      <t-form v-model="form">
        <t-form-item label="平台名称" prop="platformName">
          <t-input v-model="form.platformName" placeholder="请输入平台名称" />
        </t-form-item>
        <t-form-item label="平台网址" prop="platformUrl" help="具体到某一场的网址">
          <t-input v-model="form.platformUrl" placeholder="请输入平台网址" />
        </t-form-item>
        <t-form-item label="账户名称" prop="platformAccount">
          <t-input v-model="form.platformAccount" placeholder="请输入平台账号" />
        </t-form-item>
      </t-form>
    </div>
    <template #footer>
      <div class="flex justify-end gap-4">
        <t-button theme="default" @click="onCancel">取消</t-button>
        <t-button theme="success" @click="onSubmit">确定</t-button>
      </div>
    </template>
  </t-dialog>
</template>
<style scoped lang="less"></style>
